package com.hepinghospital.user.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.AtyMedicineAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.PrescriptionResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Description
 * Created by lbj on 2021/8/26 14:25
 */

public class AtyOrderMedicineDetailActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_chufang_number)
    TextView tvChufangNumber;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @BindView(R.id.tv_patient_age)
    TextView tvPatientAge;
    @BindView(R.id.identity_num)
    TextView identityNum;
    @BindView(R.id.tv_patient_no)
    TextView tvPatientNo;
    @BindView(R.id.tv_diagnose)
    TextView tvDiagnose;
    @BindView(R.id.iv_openDoctorSign_date)
    TextView ivOpenDoctorSignDate;
    @BindView(R.id.iv_auditorSignImg_date)
    TextView ivAuditorSignImgDate;
    @BindView(R.id.tv_time_kaifeng)
    TextView tvTimeKaifeng;
    @BindView(R.id.treat_department)
    TextView treatDepartment;
    @BindView(R.id.rv_medicine)
    RecyclerView rvMedicine;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    //    @BindView(R.id.tv_doctorName)
//    TextView tvDoctorName;
    @BindView(R.id.tv_compound_doctor_name)
    TextView tvCompoundDoctorName;
    @BindView(R.id.tv_distribute_doctor_name)
    TextView tvDistributeDoctorName;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_style_name)
    TextView tvStyleName;
    @BindView(R.id.tv_receive_name)
    TextView tvReceiveName;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.cl_address)
    ConstraintLayout clAddress;
    @BindView(R.id.iv_auditorSignImg)
    ImageView ivAuditorSignImg;
    @BindView(R.id.iv_openDoctorSignImg)
    ImageView ivOpenDoctorSignImg;
    @BindView(R.id.btn_cancel)
    TextView btnCancel;
    @BindView(R.id.btn_pay)
    TextView btnPay;
    @BindView(R.id.btn_refund)
    TextView btnRefund;

    private String hospitalPhone, orderId, receiverAddress, receiverPhone, preId;
    List<PrescriptionResponse.Prescription> list = new ArrayList<>();
    AtyMedicineAdapter adapter;
    boolean isUpdate;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_medicine_detail;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        tvTitle.setText("订单详情");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMedicine.setLayoutManager(manager);
        adapter = new AtyMedicineAdapter(this, list);
        rvMedicine.setAdapter(adapter);
        btnCancel.setOnClickListener(v -> updatePrescriptionStatus(preId, "7"));
        btnPay.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("orderId", orderId);
            startActivity(MedicineDetailActivity.class, bundle);
        });
        btnRefund.setOnClickListener(v -> {
            updatePrescriptionStatus(preId, "8");
        });
        btn_back.setOnClickListener(v -> {
            if (isUpdate) {
                setResult(RESULT_OK);
            }
            finish();
        });
    }

    @Override
    protected void initData() {
        orderId = getIntent().getStringExtra("orderId");
        getMedicineOrderDetail(orderId);
    }

    private void updatePrescriptionStatus(String prescriptionId, String status) {
        showLoadingDialog(mContext);
        Map<String, Object> map = new HashMap<>();
        map.put("id", prescriptionId);
        map.put("status", status);
        RestProxy.getInstance().updatePrescriptionStatus(map, new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean s) {
                dismissLoadingDialog();
                if (s) {
                    isUpdate = true;
                    getMedicineOrderDetail(orderId);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
                dismissLoadingDialog();
            }
        });
    }

    private void getMedicineOrderDetail(String orderId) {
        showLoadingDialog(mContext);
        RestProxy.getInstance().getMedicineOrderDetail(orderId, new Observer<PrescriptionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PrescriptionResponse prescriptionResponse) {
                dismissLoadingDialog();
                PrescriptionResponse data = prescriptionResponse;
                if ("3".equals(prescriptionResponse.receiveType)) {//医院自取
                    tvStyleName.setText("院内自取");
                    tvReceiveName.setText(data.hospitalName);
                } else if ("0".equals(prescriptionResponse.receiveType)) {//未审核
                    tvStyleName.setText("");
                    tvReceiveName.setText("");
                } else {
                    tvStyleName.setText("物流配送");
                    tvReceiveName.setText(data.receiverName + "," + data.receiverPhone + "," + data.receiverAddress);
                }
                tvChufangNumber.setText("处方编号：" + prescriptionResponse.preId);
//                tvDoctorName.setText("开方医师：" + prescriptionResponse.doctorName);
                ImageLoaderHelper.getInstance().GlideImageLoader(mContext, prescriptionResponse.openDoctorSignImg, ivOpenDoctorSignImg);

//                byte[] decodedString = Base64.decode(prescriptionResponse.openDoctorSignImg, Base64.DEFAULT);
//                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
//                ivOpenDoctorSignImg.setImageBitmap(decodedByte);
//
//                byte[] decodedString1 = Base64.decode(prescriptionResponse.auditorSignImg, Base64.DEFAULT);
//                Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString1, 0, decodedString1.length);
//                ivAuditorSignImg.setImageBitmap(bitmap);

                tvCompoundDoctorName.setText("调配：" + prescriptionResponse.compoundDoctorName + " " + prescriptionResponse.compoundTime);
                tvDistributeDoctorName.setText("发药：" + prescriptionResponse.distributeDoctorName + " " + prescriptionResponse.distributeTime);
                tvTimeKaifeng.setText("开方日期：" + prescriptionResponse.preTime);
                tvAllPrice.setText(prescriptionResponse.prescriptionAmount);
                hospitalPhone = prescriptionResponse.hospitalPhone;
                tvPatientNo.setText("门诊病历号：" + prescriptionResponse.medicalId);
                setStatusColor(tvStatus, data.status);
                tvStatus.setText(data.statusName);
                tvPatientName.setText("就诊人：" + data.patientName);
                tvPatientSex.setText("性别：" + data.patientSex);
                tvPatientAge.setText("年龄：" + data.patientAge + "岁");
                identityNum.setText("身份证：" + data.patientIdcard);
                treatDepartment.setText("就诊科室：" + data.openDoctorDept);
                ivOpenDoctorSignDate.setText(data.createTime);
                ivAuditorSignImgDate.setText(data.passTime);
                tvDiagnose.setText("主诊诊断：" + prescriptionResponse.preAppend + "-" + prescriptionResponse.icd + "-" + prescriptionResponse.tailAppend);
                tvNumber.setText(data.orderId);
                tvCreateTime.setText(data.createTime);
                tvPayTime.setText(data.payTime);
                preId = prescriptionResponse.preId;
                if ("1".equals(prescriptionResponse.status)) {
                    btnCancel.setVisibility(View.VISIBLE);
                    btnPay.setVisibility(View.VISIBLE);
                    btnRefund.setVisibility(View.GONE);
                } else if ("3".equals(prescriptionResponse.status) || "6".equals(prescriptionResponse.status)) {
                    btnCancel.setVisibility(View.GONE);
                    btnPay.setVisibility(View.GONE);
                    btnRefund.setVisibility(View.VISIBLE);
                } else {
                    btnCancel.setVisibility(View.GONE);
                    btnPay.setVisibility(View.GONE);
                    btnRefund.setVisibility(View.GONE);
                }

                list.clear();
                list.addAll(prescriptionResponse.westernNameDtoList);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void onBackPressed() {
        if (isUpdate) {
            setResult(RESULT_OK);
        }
        super.onBackPressed();
    }

    private void setStatusColor(TextView tvStatus, String status) {
        switch (status) {
            case "5":
            case "7":
            case "11":
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.ff999999));
                break;

            default:
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.fff54c4c));
        }
    }


    private String getStatus(int status) {
        switch (status) {
            case 401:
                return "待支付";
            case 402:
                return "未发货";
            case 403:
                return "已发货";
            case 404:
                return "已收货";
            case 405:
                return "待领取";
            default:
                return "";
        }
    }
}
